package com.mimc.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.mimc.common.constant.AppConstants;
import com.mimc.common.constant.CacheConstants;
import io.jboot.aop.annotation.Bean;
import io.jboot.utils.CacheUtil;
import io.jboot.utils.HttpUtil;

import java.util.HashMap;
import java.util.Map;

@Bean
public class ShMimcService {
    @Inject
    private ShSysConfigService shSysConfigService;
    //获取token
    public String getToken(Long userId,Boolean cache){
        if(cache){
            String res= CacheUtil.get(CacheConstants.APP_MIMC_TOKEN,CacheConstants.APP_MIMC_ACCOUNT_KEY_PREFIX+userId);
            if(res==null){
                res=fetchToken(userId);
                JSONObject jsonObject= JSON.parseObject(res);
                if(jsonObject.getInteger("code")==200){
                    CacheUtil.put(CacheConstants.APP_MIMC_TOKEN,CacheConstants.APP_MIMC_ACCOUNT_KEY_PREFIX+userId,res);
                }
            }
            return res;
        }else{
            String res=fetchToken(userId);
            JSONObject jsonObject= JSON.parseObject(res);
            if(jsonObject.getInteger("code")==200){
                CacheUtil.put(CacheConstants.APP_MIMC_TOKEN,CacheConstants.APP_MIMC_ACCOUNT_KEY_PREFIX+userId,res);
            }
            return res;
        }
    }
    private String fetchToken(Long userId){
        String url="https://mimc.chat.xiaomi.net/api/account/token";
        HashMap<String, Object> paramMap = new HashMap<>();
        String appId=shSysConfigService.getConfigValueByKey("mimc.appid");
        String appKey=shSysConfigService.getConfigValueByKey("mimc.appkey");
        String appSecret=shSysConfigService.getConfigValueByKey("mimc.appsecret");
        String regionKey=shSysConfigService.getConfigValueByKey("mimc.regionkey");
        paramMap.put("appId",appId);
        paramMap.put("appKey",appKey);
        paramMap.put("appSecret",appSecret);
        paramMap.put("regionKey",regionKey);
        paramMap.put("appAccount", userId+"");
        Map<String,String> headers=new HashMap<>();
        headers.put("Content-Type","application/json");
        String res=HttpUtil.httpPost(url,paramMap,headers);
        return res;
    }
}
